package com.sneaker.shower.socket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sneaker.shower.socket.common.PSWsRequest;
import com.sneaker.shower.socket.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * <h1>Handler</h1>
 * <pre>
 * @Description
 * </pre>
 *
 * @Author lopo
 * @Date 2018/10/22
 */
public abstract class Handler {
    private static ObjectMapper objectMapper = new ObjectMapper();
    private Logger logger = LoggerFactory.getLogger(Handler.class);

    public void handle(String message) {
        logger.info("consume message :{}", message);
        try {
            PSWsRequest request = objectMapper.readValue(message, PSWsRequest.class);
            handle(request);
        } catch (IOException e) {
            logger.error("deserialiser fail:", e);
        }
    }

    public void handle(PSWsRequest request) {
        String orgId = (String) request.getHeader().get(PSWsRequest.HEADER_ORG_ID);
        String accountId = (String) request.getHeader().get(PSWsRequest.HEADER_ACCOUNT_ID);
        ChannelSign channelSign = new ChannelSign(accountId, orgId);
        Group<Channel> channelGroup = groupRepository().get(channelSign);
        if (channelGroup != null) {
            channelGroup.group().stream().forEach((e) -> {
                e.send(request);
            });
        }
    }

    public abstract Repository<Group<Channel>> groupRepository();
}
